import React, { useState } from 'react';
import s from './style.module.less';
import {
  Radio,
  Datetime,
  Textarea,
  Input,
  Checkbox,
  Collapse,
  Form,
  Confirm,
  Switch,
  Select,
} from '@knownsec/react-component';
import cn from 'classnames';
import Helper from '@/components/Helper';
import recursionForm from '@/common/recursionForm';
// import SelectAnt from '@/components/SelectAnt';

const { Panel } = Collapse;
const { RangePicker } = Datetime;
const layout = {};
let defaultData = {
  is_solo: false,
  requests_per_sec: ['0'],
  concurrency: ['0'],
  is_filter_by_query_key: ['true'],
  request_timeout: ['0'],
  crawler_included_urls: null,
  crawler_excluded_urls: null,

  site_login: 1,
  login_method: 0,
  login_json_action_url: '',
  login_json_postdata: '',
  login_form_action_url: '',
  login_form_postdata: '',

  is_http_auth_enabled: 1,
  http_auth_username: '',
  http_auth_password: '',

  is_proxy_enabled: 1,
  proxy_scheme: '',
  proxy_host: '',
  proxy_port: '',
  is_proxy_need_auth: 1,
  proxy_username: '',
  proxy_password: '',

  request_http_headers: '',
  request_cookie: '',
  request_user_agent: '',
  is_deep_malscan:false,
};
export default function Advanced({ formData, formRef, params = {}, onChange }) {
  const [itemHeight, setItemHeight] = useState({
    site_login: false,
    is_http_auth_enabled: false,
    is_proxy_enabled: false,
    is_proxy_need_auth: false,
    is_solo: false,
  });
  const [isLoginJson, setIsLoginJson] = useState(true);
  const [urlLength, setUrlLength] = useState(false);
  const createForm = formRef;
  const onOffArr = [
    'site_login',
    'is_http_auth_enabled',
    'is_proxy_enabled',
    'is_proxy_need_auth',
    'is_solo',
  ];
  const initData = () => {
    createForm.current.setFieldsValue({
      login_method: defaultData.login_method,
    });
    // setIsLoginJson(defaultData.login_method);
    // props浅拷贝导致了CM-2935数据问题,目前数据结构比较深暂时不动
    let advance_config = formData.advance_config;
    const included = advance_config.crawler_included_urls;
    const excluded = advance_config.crawler_excluded_urls;
    if (Array.isArray(included)) {
      advance_config.crawler_included_urls = included.join('\n');
    }
    if (Array.isArray(excluded)) {
      advance_config.crawler_excluded_urls = excluded.join('\n');
    }
    const onOffObj = {};
    onOffArr.forEach((e) => {
      advance_config[e] = advance_config[e] ? 1 : 0;
      onOffObj[e] = Boolean(advance_config[e]);
    });
    setItemHeight(onOffObj);
    const arr = ['requests_per_sec', 'concurrency', 'is_filter_by_query_key', 'request_timeout'];
    for (let item in advance_config) {
      if (arr.includes(item)) {
        advance_config[item] = [].concat(advance_config[item] + '')
      }
    }
    createForm.current.setFieldsValue(advance_config);
    setIsLoginJson(advance_config.login_method);
  };
  const onValues = (newItem) => {
    const values = Object.keys(newItem).reduce((total, key) => {
      let value
      if (newItem[key].selectedItem) {
        if (newItem[key].selectedItem.length > 0) {
          value = [newItem[key].selectedItem[0].value]
        } else if (newItem[key].selectedItem.length === 0) {
          value = newItem[key]
        }
      } else if (Object.keys(newItem[key]).indexOf('value') > -1) {
        value = newItem[key].value
      } else {
        value = newItem[key]
      }
      total[key] = value
      return total
    }, {})
    const selKey = Object.keys(values)[0];
    createForm.current.setFieldsValue(values);

    if (
      'crawler_included_urls' in values ||
      'crawler_excluded_urls' in values
    ) {
      values[selKey] =values[selKey]? values[selKey].split('\n'):[];
    }
    //开关
    if ('login_method' in values) {
      setIsLoginJson(values.login_method);
    }
    if (onOffArr.includes(selKey)) {
      values[selKey] = Boolean(values[selKey]);
      setItemHeight({ ...itemHeight, [selKey]: Boolean(values[selKey]) });
    }
    const val = Object.keys(values).reduce((prev, cur) => {
      if (Array.isArray(values[cur])) {
        if (values[cur][0] === 'true') {
          prev[cur] = true
        } else if (values[cur][0] === 'false') {
          prev[cur] = false
        } else {
          prev[cur] = values[cur][0]
        }
      } else {
        prev[cur] = values[cur]
      }
      return prev
    }, {})
    onChange('advance_config', val);
  };
  const loginType = () => {
    const typeArr = {
      form: <>
        <Form.Item
          name="login_form_action_url"
          label={
            <span>
               登录URL
              <Helper
                className="paddingHelp"
                placement="top"
                overlay="请填写登录页面的URL,例如：http://example.com/login"
              ></Helper>
            </span>
          }
          rules={[{ required: true, message: '请输入登录URL' }]}
          className={s.item}
        >
          <Input
            disabled={!itemHeight.is_solo && params.type === 'solo'}
            pro
            className={s.w_30}
            placeholder="请输入"
            autoComplete={'off'}
          ></Input>
        </Form.Item>
        <Form.Item
          name="login_form_postdata"
          label={
            <span>
                            POST认证参数
              <Helper
                className="paddingHelp"
                placement="top"
                overlay={`请按照以下格式填写:u=user&p=passwd`}
              ></Helper>
            </span>
          }
          rules={[{ required: true, message: '请输入POST认证参数' }]}
          className={s.item}
        >
          <Input
            disabled={!itemHeight.is_solo && params.type === 'solo'}
            pro
            className={s.w_30}
            placeholder="请输入"
            autoComplete={'off'}
          ></Input>
        </Form.Item>
      </>,
      json:<>
        <Form.Item
          name="login_json_action_url"
          label={
            <span>
                            登录URL
              <Helper
                className="paddingHelp"
                placement="top"
                overlay="请填写登录页面的URL,例如：http://example.com/login"
              ></Helper>
            </span>
          }
          rules={[{ required: true, message: '请输入登录URL' }]}
          className={s.item}
        >
          <Input
            disabled={!itemHeight.is_solo && params.type === 'solo'}
            pro
            className={s.w_30}
            placeholder="请输入"
            autoComplete={'off'}
          ></Input>
        </Form.Item>
        <Form.Item
          name="login_json_postdata"
          label={
            <span>
                            POST认证参数
              <Helper
                className="paddingHelp"
                placement="top"
                overlay={`请填写JSON格式:{"u":"admin","p":"qqq"}`}
              ></Helper>
            </span>
          }
          rules={[{ required: true, message: '请输入POST认证参数' }]}
          className={s.item}
        >
          <Textarea
            disabled={!itemHeight.is_solo && params.type === 'solo'}
            pro
            className={cn(s.w_30, s.bors)}
            placeholder='{"u":"admin","p":"ABCabc123"}'
          ></Textarea>
        </Form.Item>
      </>,
      cookie:<>
        <Form.Item
          name="request_cookie"
          rules={[{ required: true, message: '请输入登录Cookie' }]}
          label={
            <span>
                            Cookie
              <Helper
                className="paddingHelp"
                placement="top"
                overlay="通过已经登录网站后得到的Cookie来检测网站，设置用户的Cookie就对用户的权限能访问到的网页进行检测，一般设置管理员用户的Cookie"
              ></Helper>
            </span>
          }
          className={s.item}
        >
          <Textarea
            pro
            disabled={!itemHeight.is_solo && params.type === 'solo'}
            className={cn(s.w_30, s.h_6, s.bors)}
            placeholder="例如：Chrome可以右键审查元素，Application选项中找到Cookies,全选复制即可。不同浏览器不同版本可能有所不同。"
          ></Textarea>
        </Form.Item>
      </>,
      headers:<>
        {' '}
        <Form.Item
          name="request_http_headers"
          rules={[{ required: true, message: '请输入登录headers' }]}
          label={
            <span>
                            headers
              <Helper
                className="paddingHelp"
                placement="top"
                overlay="通过已经登录网站后得到的headers来检测网站，设置用户的headers就对用户权限能访问到的网页进行检测，一般设置管理员用户的headers"
              ></Helper>
            </span>
          }
          className={s.item}
        >
          <Textarea
            pro
            disabled={!itemHeight.is_solo && params.type === 'solo'}
            className={cn(s.w_30, s.h_6, s.bors)}
            placeholder="每一行输入一组key和value。例如；&#13;&#10;Acceot:*/*&#13;&#10;Accept-Encoding:gzip,deflate,br&#13;&#10;Host:localhost:3000"
          ></Textarea>
        </Form.Item>
      </>,
    };
    return typeArr[isLoginJson];
  };
  React.useEffect(() => {
    initData();
    if(formData.target_urls.length!==1){
      setUrlLength(true)
      createForm.current.setFieldsValue({site_login:false,is_http_auth_enabled:false,is_proxy_enabled:false,request_user_agent:''});
      setItemHeight({
        site_login: false,
        is_http_auth_enabled: false,
        is_proxy_enabled: false,
        is_proxy_need_auth: false,
      })
    }
  }, []);
  return (
    <div className={s.monitorForm}>
      <Form
        {...layout}
        ref={createForm}
        initialValues={defaultData}
        name="control-ref"
        onValuesChange={(changedValues) => {
          if("is_solo" in changedValues) {
            const value=changedValues.is_solo
            let msg=value?'启用后，此业务系统检测配置将单独控制，不受任务组配置影响，您确定要启用吗？':'关闭后，此业务系统检测将按对应任务组配置检测，您确定要关闭吗？'
            Confirm({
              title: '提示',
              pro: true,
              className: s.dialogName,
              message: <div className="confirmbox">{msg}</div>,
              onconfirm:  () => {onValues(changedValues);},
              oncancel: () => {
                createForm.current.setFieldsValue({is_solo:!value});
              },
            });
          }else{
            onValues(changedValues);
          }
        }}
      >
        {params.type === 'solo' && (
          <Form.Item
            name="is_solo"
            label={
              <span>
                                启用单个业务系统设置
                <Helper
                  className="paddingHelp"
                  placement="top"
                  overlay="开启后，监测此站点时将忽略任务组相关配置。"
                ></Helper>
              </span>
            }
            className={s.itemSolo}
            valuePropName="checked"
          >
            <Switch pro></Switch>
          </Form.Item>
        )}
        {/* 策略设置 */}
        <Collapse className={s.Collapse} defaultActiveKey={1}>
          <Panel header="策略设置" key="1">
            <div className={s.itemBox}>
              <Form.Item
                name="requests_per_sec"
                label={
                  <span>
                                        每秒最大请求数
                    <Helper
                      className="paddingHelp"
                      placement="top"
                      overlay="限制该任务扫描时，每秒能发送的最大请求数。"
                    ></Helper>
                  </span>
                }
                className={s.item}
              >
                <Select
                  pro
                  disabled={!itemHeight.is_solo && params.type === 'solo'}
                  option={[
                    { label: '自动', value: '0' },
                    { label: '180', value: '180' },
                    { label: '60', value: '60' },
                    { label: '30', value: '30' },
                    { label: '20', value: '20' },
                    { label: '10', value: '10' },
                  ]}
                  className={s.sel}
                />
              </Form.Item>
              <Form.Item
                name="concurrency"
                label={
                  <span>
                                        并发数量
                    <Helper
                      className="paddingHelp"
                      placement="top"
                      overlay="建议默认，并发数量越大，CPU和内存占用率越高"
                    ></Helper>
                  </span>
                }
                className={s.item6}
              >
                <Select
                  pro
                  disabled={!itemHeight.is_solo && params.type === 'solo'}
                  option={[
                    { label: '自动', value: '0' },
                    { label: '20', value: '20' },
                    { label: '10', value: '10' },
                    { label: '5', value: '5' },
                  ]}
                  className={s.sel}
                />
              </Form.Item>
              <Form.Item
                name="is_filter_by_query_key"
                label="同参数去重"
                className={s.item6}
              >
                <Select
                  pro
                  disabled={!itemHeight.is_solo && params.type === 'solo'}
                  option={[
                    { label: '是', value: 'true' },
                    { label: '否', value: 'false' },
                  ]}
                  className={s.sel}
                />
              </Form.Item>
              <Form.Item name="request_timeout" label="超时设置(秒)" className={s.item6}>
                <Select
                  pro
                  disabled={!itemHeight.is_solo && params.type === 'solo'}
                  option={[
                    { label: '自动', value: '0' },
                    { label: '180', value: '180' },
                    { label: '60', value: '60' },
                    { label: '30', value: '30' },
                    { label: '20', value: '20' },
                    { label: '10', value: '10' },
                  ]}
                  className={s.sel}
                />
              </Form.Item>
            </div>
            <div className={s.helpBox}>
              <Form.Item
                name="crawler_included_urls"
                label="需额外监测页面入口"
                className={s.item}
              >
                <Textarea
                  disabled={!itemHeight.is_solo && params.type === 'solo'}
                  className={s.textArea}
                  placeholder="请输入需额外监测URL入口的关键参数，一行一个"
                ></Textarea>
              </Form.Item>
              <Helper
                className={s.helper}
                placement="top"
                overlay="如您需要监测地址入口是'https://www.admin.com/test/'，可在此输入'/test'即可。"
              ></Helper>
            </div>
            
            <div className={s.helpBox}>
              <Form.Item
                name="crawler_excluded_urls"
                label="不需监测页面"
                className={s.item}
              >
                <Textarea
                  disabled={!itemHeight.is_solo && params.type === 'solo'}
                  className={s.textArea}
                  placeholder="请输入不需监测URL的关键参数，一行一个"
                ></Textarea>
              </Form.Item>
              <Helper
                className={s.helper}
                placement="top"
                overlay="系统自动过滤监测匹配到参数的URL，如您不需要监测地址是'https://www.admin.com/test/'，可在此输入'/test'即可。"
              ></Helper>
            </div>
           
          </Panel>
        </Collapse>
        {/* 信息设置 */}
        <Collapse className={s.Collapse} defaultActiveKey={1}>
          <Panel header="信息设置" key="1">
            {/*  */}
            <Form.Item name="site_login" label="网站登录" className={s.title}
              valuePropName="checked"
            >
              <Switch
                pro
                disabled={(!itemHeight.is_solo && params.type === 'solo')||urlLength}
              ></Switch>
            </Form.Item>
            <div
              className={s.infoBox}
              style={{ height: itemHeight.site_login ? 'auto' : 0 }}
            >
              <Form.Item
                name="login_method"
                label="登录方式"
                className={cn(s.item, s.itemFirst0, s.itemFirst)}
              >
                <Radio.Group className={s.radioBorder}>
                  <Radio
                    disabled={!itemHeight.is_solo && params.type === 'solo'}
                    value={'form'}
                    className={s.radio0}
                  >表单登录
                  </Radio>
                  <Radio
                    disabled={!itemHeight.is_solo && params.type === 'solo'}
                    value={'json'}
                    className={s.radio0}
                  >JSON登录
                  </Radio>
                  <Radio
                    disabled={!itemHeight.is_solo && params.type === 'solo'}
                    value={'cookie'}
                    className={s.radio0}
                  >Cookie<Helper
                      className="paddingHelp"
                      placement="top"
                      overlay="通过已经登录网站后得到的Cookie来检测网站，设置用户的Cookie就对用户权限能访问到的网页进行检测，一般设置管理员用户的Cookie。"
                    ></Helper>
                  </Radio>
                  <Radio
                    disabled={!itemHeight.is_solo && params.type === 'solo'}
                    value={'headers'}
                    className={s.radio0}
                  >Headers<Helper
                      className="paddingHelp"
                      placement="top"
                      overlay="通过已经登录网站后得到的Headers来检测网站，设置用户的Headers就对用户权限能访问到的网页进行检测，一般设置管理员用户的Headers。"
                    ></Helper>
                  </Radio>
                </Radio.Group>
              </Form.Item>
              {loginType()}
            </div>
            {/*  */}
            <Form.Item name="is_http_auth_enabled" label="HTTP认证" className={s.title}
              valuePropName="checked"
            >
              <Switch
                pro
                disabled={(!itemHeight.is_solo && params.type === 'solo')||urlLength}
              ></Switch>
            </Form.Item>
            <div
              className={s.infoBox}
              style={{ height: itemHeight.is_http_auth_enabled ? 'auto' : 0 }}
            >
              <div className={s.text}>支持BASIC、Digest</div>
              <Form.Item
                name="http_auth_username"
                label="用户名"
                className={cn(s.item, s.itemFirst)}
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input
                  disabled={!itemHeight.is_solo && params.type === 'solo'}
                  pro
                  className={s.w_30}
                  placeholder="请输入"
                  autoComplete={'off'}
                ></Input>
              </Form.Item>
              <Form.Item
                name="http_auth_password"
                rules={[{ required: true, message: '请输入密码' }]}
                label="密码"
                className={s.item}
              >
                <Input
                  disabled={!itemHeight.is_solo && params.type === 'solo'}
                  pro
                  className={s.w_30}
                  placeholder="请输入"
                  autoComplete={'off'}
                ></Input>
              </Form.Item>
            </div>
            {/*  */}
            <Form.Item name="is_proxy_enabled" label="代理服务器" className={s.title}
              valuePropName="checked"
            >
              <Switch
                pro
                disabled={(!itemHeight.is_solo && params.type === 'solo')||urlLength}
              ></Switch>
            </Form.Item>
            <div
              className={s.infoBox}
              style={{ height: itemHeight.is_proxy_enabled ? 'auto' : 0 }}
            >
              <Form.Item
                name="proxy_scheme"
                rules={[{ required: true, message: '请输入协议' }]}
                label="协议"
                className={cn(s.item, s.itemFirst)}
              >
                <Input
                  disabled={true}
                  pro
                  className={s.w_30}
                  placeholder="请输入"
                  autoComplete={'off'}
                ></Input>
              </Form.Item>
              <Form.Item
                rules={[{ required: true, message: '请输入IP' }]}
                name="proxy_host"
                label="IP"
                className={s.item}
              >
                <Input
                  disabled={!itemHeight.is_solo && params.type === 'solo'}
                  pro
                  className={s.w_30}
                  placeholder="请输入"
                  autoComplete={'off'}
                ></Input>
              </Form.Item>
              <Form.Item
                rules={[{ required: true, message: '请输入端口' }]}
                name="proxy_port"
                label="端口"
                className={s.item}
              >
                <Input
                  disabled={!itemHeight.is_solo && params.type === 'solo'}
                  pro
                  className={s.w_30}
                  placeholder="请输入"
                  autoComplete={'off'}
                  type='number'
                ></Input>
              </Form.Item>
              <Form.Item
                name="is_proxy_need_auth"
                className={cn(s.item, s.itemNoLabel)}
                valuePropName="checked"
              >
                <Checkbox
                  disabled={!itemHeight.is_solo && params.type === 'solo'}
                  pro
                >
                                    此代理服务器需要身份验证
                </Checkbox>
              </Form.Item>
              {itemHeight.is_proxy_need_auth ? (
                <>
                  <Form.Item
                    name="proxy_username"
                    label="用户名"
                    rules={[{ required: true, message: '请输入用户名' }]}
                    className={s.item}
                  >
                    <Input
                      disabled={!itemHeight.is_solo && params.type === 'solo'}
                      pro
                      className={s.w_30}
                      placeholder="请输入"
                      autoComplete={'off'}
                    ></Input>
                  </Form.Item>
                  <Form.Item
                    name="proxy_password"
                    rules={[{ required: true, message: '请输入密码' }]}
                    label="密码"
                    className={s.item}
                  >
                    <Input
                      disabled={!itemHeight.is_solo && params.type === 'solo'}
                      pro
                      className={s.w_30}
                      placeholder="请输入"
                    ></Input>
                  </Form.Item>
                </>
              ) : null}
            </div>
            {/*  */}

            <Form.Item
              name="request_user_agent"
              label={
                <span>
                                    User Agent
                  <Helper
                    className="paddingHelp"
                    placement="top"
                    overlay="扫描网页时HTTP头部User-Agent的值"
                  ></Helper>
                </span>
              }
              className={s.col4}
            >
              <Input
                disabled={(!itemHeight.is_solo && params.type === 'solo')||urlLength}
                pro
                className={s.w_30}
                placeholder="请输入"
                autoComplete={'off'}
              ></Input>
            </Form.Item>
          </Panel>
        </Collapse>
        {/* 专家配置 */}
        <Collapse className={s.Collapse} defaultActiveKey={1}>
          <Panel header="专家配置" key="1">
            <Form.Item
              name="is_deep_malscan"
              className={cn(s.item, s.itemNoLabel2)}
              valuePropName="checked"
            >
              <Checkbox
                disabled={!itemHeight.is_solo && params.type === 'solo'}
                pro
              >
                高级静态挂马检测<Helper
                  className="paddingHelp"
                  placement="top"
                  overlay="除了使用云特征的恶意挂马库检测网站以外，还检测网站页面是否存在可疑的恶意挂马网页脚本和嵌入的第三方恶意javascript脚本。"
                ></Helper>
              </Checkbox>
            </Form.Item>

          </Panel>
        </Collapse>
      </Form>
    </div>
  );
}
